	/*
 * Copyrights of MYeBills. Do not copy or distribute without permissions.
 *
 * TODO Exception logging
 */

package com.myebills.ebpsfrontend.cust.maxis;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.Color;
import java.util.*;
import java.text.*;

import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.AccountHomeImpl;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.statement.StatementSection;
import com.checkfree.isolutions.statement.persist.Statement;
import com.checkfree.isolutions.statement.persist.StatementHomeImpl;
import com.checkfree.isolutions.utility.CFiError;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.PageSize;

public class CusCallTaggingPDF extends PdfPageEventHelper {
    static Font fCourier = null, fCourierTitle = null;
    static Font fCourierHeader = null;

    // Application required property values
    static final String CONFIG_FILE = "/properties/MaxisPdfGeneration.properties";
    static final java.util.Properties config = new java.util.Properties();

    private static String DATE_SEP = "/";
    private static final int indentPadSize=13;
    private static final int padRight=6;
    private static final String PATH_OUTPUT = "";

    //header - type 01
	private static final String PP_PATH_IMG_HEADER = "cus/images/header01.jpg";
	private static final String PP_PATH_IMG_FOOTER = "cus/images/footer01.jpg";
    private static final String TEXT_HEADER_PAGE_NO = "pp.text.header.pageNo";
    private static final String TEXT_HEADER_DATE = "pp.text.header.date";
    private static final String TEXT_HEADER_CDSNO = "pp.text.header.cdsno";
    private static final String TEXT_HEADER_CLIENTCD = "pp.text.header.clientcd";
    private static final String TEXT_HEADER_SMF = "pp.text.header.smf";

	//Body

    private static final String TEXT_BODY_CNTDT = "cnt.text.body.cntdt";


    // metadata
    private static final String META_TITLE = "Maxis eBill";
    private static final String META_SUBJECT = "Maxis eBill";
    private static final String META_KEYWORDS = "metadata,postpaid, ebill";
    private static final String META_CREATOR = "MYeBills EBPS";
    private static final String META_AUTHOR = "MYeBills";

    // private variables
    private String accountNo = null;
    private String phoneNo = null;
    private String callType = null;
    private ArrayList phoneBookList = null;
    private Statement statement = null;
    private double amount = 0.00;

    private String pStrDate = null;
    private Statement pStmt = null;
    private boolean bPdfDownload = false;
    OutputStream pdfOs = null;

 	//private Color colorMBBYellow = new Color (248, 240, 0);
	private Color colorTNBRed = new Color (249, 198, 170);
	private Color colorTNBBlue = new Color (209, 206, 221);
	private Color colorGrey = new Color (214, 216, 211);
    /**214     216     211
     * This is for testing purpose only
     *
     * @param args
     */
    public static void main(String[] args) {
        String mer = "Maybank";
        String date = "2008-03-01";

        //CusCallTaggingPDF tnb = new CusCallTaggingPDF(mer, "01810006626208", "2008-03-01");
        //tnb.buildDocument();
    }

    /**
     * Constructor to initialize the class.
     * Use this constructor to output PDF statement in local directory
     *
     * @param merchant
     *            the merchant external key
     * @param accountNo
     *            the account no of the statement to generate
     * @param strDate
     *            statement date
     *
     */
    public CusCallTaggingPDF(String phoneNo, String accountNo, ArrayList phoneBookList,Statement statement,double amount,String callType) {
        this.phoneNo = phoneNo;
        this.accountNo = accountNo;
        this.phoneBookList = phoneBookList;
        this.statement = statement;
        this.amount = amount;
        this.callType = callType;

    }
/**
 * Constructor to initialize the class.
 * Use this constructor to get the outputStream and write it to the desired output channel. i.e to the http
 *
 * @param merchant the merchant external key
 * @param accountNo the account no of the statement to generate
 * @param strDate statement date
 * @param os the OutputStream where the statement bytestreams will be directed to
 */
    public CusCallTaggingPDF(String phoneNo, String accountNo, ArrayList phoneBookList,Statement statement,double amount,String callType,OutputStream os) {
        this(phoneNo, accountNo, phoneBookList,statement,amount,callType);
        bPdfDownload = true;
        pdfOs = os;
    }

 /**
 *  builds the PDF statement
 *
 */
    public void buildDocument() {

        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4,10,10,180,50);

        try {

            // step 2: creation of the writer
            // File name = <accountNo>_<date>.pdf
            PdfWriter writer = null;

            // different output stream depending on how the contructor is called
            if (bPdfDownload) {
                writer = PdfWriter.getInstance(document, pdfOs);
            } else {
                writer = PdfWriter.getInstance(document, new FileOutputStream(
                        PATH_OUTPUT
                                + accountNo + "_"
                                + pStrDate.replaceAll("-", "") + ".pdf"));
            }


            // Set the document metadata
            document.addTitle(META_TITLE);
            document.addSubject(META_SUBJECT);
            document.addKeywords(META_KEYWORDS);
            document.addCreator(META_CREATOR);
            document.addAuthor(META_AUTHOR);

            fCourierTitle = new Font(Font.COURIER, 6, Font.BOLD);
            fCourierHeader = new Font(Font.COURIER, 12, Font.BOLD);
            fCourier = new Font(Font.COURIER, 11, Font.NORMAL);

            // this will activate the method OnOpenDocument(), OnCloseDocument() and OnEndPage()
            writer.setPageEvent(this);

            // step 3: we open the document
            document.open();
            addCallDetails(writer, document);

            // step 5: we close the document
            document.close();
            writer.flush();
            writer.close();

        } catch (DocumentException de) {
            System.err.println(de.getMessage());
            de.printStackTrace();
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
            ioe.printStackTrace();
        }
    }


    /**
     * add charge section
     *
     * @param writer
     * @param document
     */
        public void addCallDetails (PdfWriter writer, Document document) {

            float[] colDefSize = { 8.0F, 8.0F, 11.0F, 13.0F, 11.0F, 7.0F, 6.0F, 10.0F, 10.0F, 10.0F, 6.0F};

            try {
                PdfPTable tbl = new PdfPTable(colDefSize.length);
                tbl.setWidths(colDefSize);
                tbl.setWidthPercentage(100); // percentage


                PdfPCell cell = null;

                if(phoneBookList.size()>0){

            	    for(int i=0;i<phoneBookList.size();i++){
						ArrayList dataList = (ArrayList)phoneBookList.get(i);
						for(int j=0;j<dataList.size();j++){
							String data = (String)dataList.get(j);
							cell = new PdfPCell(new Phrase(data, fCourierTitle));
				            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
							cell.setBorder(0);
		    	            tbl.addCell(cell);
						}
					}
					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase("", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase("Total", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(PdfPCell.TOP);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(formatAmount(amount), fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(PdfPCell.TOP);
		    	    tbl.addCell(cell);

					document.add(tbl);
				}else{
					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase("No Data found", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					cell = new PdfPCell(new Phrase(" ", fCourierTitle));
				    cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
					cell.setBorder(0);
		    	    tbl.addCell(cell);

					document.add(tbl);
				}


                //ROW 4 - Call Data
				/*cell = new PdfPCell(new Phrase("27/04/08", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("21:06:40", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("JB North", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("TMB Southern", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("074811646", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("00:10:00", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("OP", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase(" ", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase(" ", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("2.00", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
				cell.setBorder(0);
                tbl.addCell(cell);

				cell = new PdfPCell(new Phrase("2.00", fCourierTitle));
	            cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
				cell.setBorder(0);
                tbl.addCell(cell);*/

                //document.add(tbl);

            } catch (DocumentException de) {
                System.err.println(de.getMessage());
                de.printStackTrace();
            }
/*
            catch (EbppException ebppe) {
                System.err.println(ebppe.getMessage());
                ebppe.printStackTrace();
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
                ex.printStackTrace();
            }
*/
        }

 /**
 * add the header portion of the statements including customer name, address etc
 * @param writer
 * @param document
 */
    public void addHeader(PdfWriter writer, Document document) {

        Rectangle page = document.getPageSize();
        float[] headerColumnDefinitionSize = { 50.0F, 40.0F, 10.0F};
        float[] headerColumnDefinitionSize0 = { 8.0F, 8.0F, 11.0F, 13.0F, 11.0F, 7.0F, 6.0F, 10.0F, 10.0F, 10.0F, 6.0F};

        float[] headerColumnDefinitionSize1 = { 55.0F, 45.0F};
        float[] headerColumnDefinitionSize2 = { 45.0F, 55.0F};
        PdfPTable header0 = null;
        PdfPTable header = null;
        PdfPTable header1 = null;
        PdfPTable header2 = null;
        PdfPCell cell = null;
		Image img = null;
        int padSize = 10;

        int pageNo = writer.getPageNumber();
        String strTmp="", strTmp2="";

        try {


		    StatementSection cfiRootSection  = statement.getRootSection();

		    String acctName = cfiRootSection.getFieldText("AccountName");
		    String stmtDate = cfiRootSection.getFieldText("StatementDate");

            /**
             * *************** HEADER**********************
             */
            header = new PdfPTable(headerColumnDefinitionSize);
            header.setWidthPercentage(100); // percentage
            header.setTotalWidth(500);
            header.getDefaultCell().setBorder(0);


            //Image Header
            img = Image.getInstance(PP_PATH_IMG_HEADER);
            img.scalePercent(50);
            cell = new PdfPCell(img, false);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
			cell.setColspan(headerColumnDefinitionSize.length);
            header.addCell(cell);

			//Row 01 : Statement Date
			cell = new PdfPCell(new Phrase("Statement Date / Tarikh Penyata", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase(": " + stmtDate, fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase("", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			//Row 02 : Phone Number
			cell = new PdfPCell(new Phrase("Phone Number / No. Telefon", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase(": " + phoneNo, fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase("", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			//Row 03 : Account Number
			cell = new PdfPCell(new Phrase("Account Name / Name. Akaun", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase(": " + acctName, fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

			cell = new PdfPCell(new Phrase("", fCourierHeader));
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
            header.addCell(cell);

            header.writeSelectedRows(0, -1, 5,
                    840, writer.getDirectContent());

            /**
             * *************** HEADER title**********************
             */
            header1 = new PdfPTable(headerColumnDefinitionSize0);
            header1.setWidthPercentage(100); // percentage
            header1.setTotalWidth(580);
            header1.getDefaultCell().setBorder(0);


			//ROW 1 - TITLE
			if(callType!=null && callType.equals("P")){
				cell = new PdfPCell(new Phrase("Personal Call Charges / Caj Panggilan", fCourierHeader));
			}else if(callType!=null && callType.equals("B")){
				cell = new PdfPCell(new Phrase("Business Call Charges / Caj Panggilan", fCourierHeader));
			}
			cell.setColspan(headerColumnDefinitionSize0.length);
			cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
			cell.setBorder(0);
			header1.addCell(cell);


			//ROW 3 - TABLE HEADER
			cell = new PdfPCell(new Phrase("Date", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Time", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Type", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("From", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("To", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Operator", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Phone No", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Number Called", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Duration", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Period", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);
			header1.addCell(cell);

			cell = new PdfPCell(new Phrase("Total", fCourierTitle));
			cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
			cell.setBorder(PdfPCell.LEFT + PdfPCell.RIGHT + PdfPCell.TOP + PdfPCell.BOTTOM);
			cell.setBackgroundColor(colorGrey);

			header1.addCell(cell);

            header1.writeSelectedRows(0, -1, 10,
                    700, writer.getDirectContent());

        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }

/**
 * add footer section of the statement
 *
 * @param writer
 * @param document
 */
    public void addFooter(PdfWriter writer, Document document) {
        Rectangle page = document.getPageSize();
        float[] footColumnDefinitionSize = { 65.0F, 18.9F, 16.1F };
        PdfPTable footer = null;
        PdfPCell cell = null;
		Image img = null;
        boolean bPostal = true;

        try {

            /**
             * **************** FOOTER ******************
             */

            footer = new PdfPTable(footColumnDefinitionSize);
            footer.setWidthPercentage(100); // percentage
            footer.setTotalWidth(840);
            footer.getDefaultCell().setBorder(0);


			// FOOTER NOTE
            img = Image.getInstance(PP_PATH_IMG_FOOTER);
            img.scalePercent(83);
            cell = new PdfPCell(img, false);
            cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
            cell.setBorder(0);
			cell.setColspan(footColumnDefinitionSize.length);
			footer.addCell(cell);

            footer.writeSelectedRows(0, -1, 5, document.bottomMargin(), writer.getDirectContent());

        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
 	}

/**
 * add the footer and header to the document when the page ended
 */
    public void onEndPage(PdfWriter writer, Document document) {

        addHeader(writer, document);
        addFooter(writer, document);

     }

/**
 * perform the necessary initialization when the document is openned
 */
    public void onOpenDocument(PdfWriter writer, Document document) {
        try {


        } catch (Exception ex) {
            System.err.println("--EXCEPTION in " + this.getClass().getName()
                    + ".buildDocument: " + ex.getClass() + " "
                    + ex.getMessage());
            ex.printStackTrace();
        } catch (Throwable t) {
            System.err.println("--EXCEPTION in " + this.getClass().getName()
                    + ".buildDocument: " + t.getClass() + " " + t.getMessage());
            t.printStackTrace();
        }
    }
/**
 *  Release PersistServer resource when the document close
 */
    public void onCloseDocument(PdfWriter writer, Document document) {

    }

/**
 * Format input date of yyyyMMdd to the output of dd<sep>MM<sep>yyyy
 * @param inDate input String of date in format yyyyMMdd
 * @param sep the date separator
 */
    public static String formatDate (String inDate, String sep) {
        return inDate.substring(6) + sep + inDate.substring(4,6) + sep + inDate.substring(0,4);
    }

    /**
     * format the given number String in pattern #,##0.<no. of decimal required>
     * @param number the number to format
     * @param noOfDecimal the no. of decimal places
     * @return format number String or the original input String if exception is thrown
     */
    public static String formatNumber(String strNumber, int noOfDecimal) {
        boolean endNegative = false;
        String number=null;
        if (strNumber.trim().endsWith("-")) {
            endNegative = true;
            number = strNumber.trim();
            number = number.substring(0, number.length()-1);

        } else {
            number = strNumber.trim();
        }
        StringBuffer sbPattern = new StringBuffer("#,##0");

        // if input is blank then just return the 0 value
        if (number == null || number.trim().equals("")) {
            if (noOfDecimal <= 0 ) {
                return "0";
            } else {
                StringBuffer temp = new StringBuffer("0.");
                for (int i=0; i < noOfDecimal; i++) {
                    temp.append("0");
                }
                return temp.toString();
            }

        }


        // format pattern with no. of decimal required
        if (noOfDecimal > 0) {
            sbPattern.append(".");
            for (int i=0; i < noOfDecimal; i++ ) {
                sbPattern.append("0");
            }
        }

        DecimalFormat df = new DecimalFormat(sbPattern.toString());
        double dValue;

        try {
            dValue = Double.parseDouble(number);
            if (endNegative) {
                return df.format(dValue) + "-";
            } else {
                return df.format(dValue);
            }

        } catch (NumberFormatException ne) {
            System.err.println(ne);
            ne.printStackTrace();
            return number;
        } catch (IllegalArgumentException ie) {
            System.err.println(ie);
            ie.printStackTrace();
            return number;
        }
    }

    /**
     * format the given number String in pattern #,##0.<no. of decimal required>
     *
     * @param number the number to format
     * @param noOfDecimal the no. of decimal places
     * @param blank indicate to return "" if input is blank (instead of returning zero value)
     *
     * @return format number String or the original input String if exception is thrown
     */
    public static String formatNumber(String number, int noOfDecimal, boolean blank) {
        if (blank==true  && (number==null || number.trim().equals("") || Float.parseFloat(number)==0 )) {
            return "";
        } else {
            return formatNumber(number, noOfDecimal);
        }
    }

    /**
     * pad zero in front of the String to to have the given length
     * @param inStr input String
     * @param len length of the output String
     * @return formatted String
     */
    public static String padZero (String inStr, int len) {
        int inLength = inStr.length();
        StringBuffer zeroStrBuff = new StringBuffer("");
        if (inLength >= len) {
            return inStr;
        } else {
            for (int i=0; i < len - inLength; i++) {
                zeroStrBuff.append("0");
            }

            return zeroStrBuff.toString()+ inStr;
        }
    }
    /**
     * return the String with left and spaces being trimmed
     * @param inStr input String
     * @return space trimmed String
     */
    public static String trimSpace(String inStr) {
        int startIndex=0, endIndex=0;
        for (int i=0; i < inStr.length(); i++) {
            if (!inStr.substring(i, i+1).equals(" ")){
                startIndex=i;
                break;
            }
        }

        for (int j=inStr.length(); j >0 ; j--) {
            if (!inStr.substring(j-1, j).equals(" ")){
                endIndex=j;
                break;
            }
        }

        return inStr.substring(startIndex, endIndex);
    }


	public static String formatAmount(double dblVal) {
	  String Amount = "0.00";
	    try {
	        NumberFormat nf = NumberFormat.getNumberInstance ();
	        nf.setMinimumFractionDigits(2);
	        nf.setMaximumFractionDigits(2);
	        Amount = nf.format(dblVal);
	    }catch (Exception e){
	    }
	  return  Amount;
	}



    /**
     * return padSize if input number string does not end with - else return 0
     * @param inStr number string
     * @param padSize pad size
     * @return pad size
     */
    public float getNegativeRightPadding (String inStr, float padSize) {
        if (inStr.trim().endsWith("-")) {
            return 0;
        } else {
            return padSize;
        }
    }
}
